<template>
  <div class="reader">
    <Loading v-show="show_loading" />

    <ul v-show="show_control" class="control bg shadow">
      <li>
        <span v-on:click="indexChange(-1) ,show_control = !show_control"> 
          <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M365.3 518.5l246 178c5.3 3.8 12.7 0 12.7-6.5v-46.9c0-10.2-4.9-19.9-13.2-25.9L465.4 512l145.4-105.2c8.3-6 13.2-15.6 13.2-25.9V334c0-6.5-7.4-10.3-12.7-6.5l-246 178c-4.4 3.2-4.4 9.8 0 13z" p-id="8028" fill="#177cb0"></path><path d="M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32z m-40 728H184V184h656v656z" p-id="8029" fill="#177cb0"></path></svg>
        </span>
        <span v-on:click="indexChange(1) ,show_control = !show_control"> 
          <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M412.7 696.5l246-178c4.4-3.2 4.4-9.7 0-12.9l-246-178c-5.3-3.8-12.7 0-12.7 6.5V381c0 10.2 4.9 19.9 13.2 25.9L558.6 512 413.2 617.2c-8.3 6-13.2 15.6-13.2 25.9V690c0 6.5 7.4 10.3 12.7 6.5z" p-id="8194" fill="#177cb0"></path><path d="M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32z m-40 728H184V184h656v656z" p-id="8195" fill="#177cb0"></path></svg>
        </span>
      </li>
    </ul>

    <ul v-show="show_control" class="chapter_control control bg shadow">
      <li>
        <p> {{ book.index + 1 }} </p>
        <span v-on:click="show_chapters = !show_chapters">
          <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32z m-40 728H184V184h656v656z" p-id="8360" fill="#177cb0"></path><path d="M492 400h184c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H492c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8zM492 544h184c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H492c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8zM492 688h184c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H492c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8z" p-id="8361" fill="#177cb0"></path><path d="M380 368m-40 0a40 40 0 1 0 80 0 40 40 0 1 0-80 0Z" p-id="8362" fill="#177cb0"></path><path d="M380 512m-40 0a40 40 0 1 0 80 0 40 40 0 1 0-80 0Z" p-id="8363" fill="#177cb0"></path><path d="M380 656m-40 0a40 40 0 1 0 80 0 40 40 0 1 0-80 0Z" p-id="8364" fill="#177cb0"></path></svg>
        </span>
      </li>
    </ul>
    
    <ul v-show="show_chapters" class="chapter_control control bg shadow">
      <li>
        <span v-show="book.chapters_sort_by == 'asc'" v-on:click="sortChapters">
          <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M839.6 433.8L749 150.5c-1.2-3.9-4.8-6.5-8.9-6.5h-77.4c-4.1 0-7.6 2.6-8.9 6.5l-91.3 283.3c-0.3 0.9-0.5 1.9-0.5 2.9 0 5.1 4.2 9.3 9.3 9.3h56.4c4.2 0 7.8-2.8 9-6.8l17.5-61.6h89l17.3 61.5c1.1 4 4.8 6.8 9 6.8h61.2c1 0 1.9-0.1 2.8-0.4 2.4-0.8 4.3-2.4 5.5-4.6 1.1-2.2 1.3-4.7 0.6-7.1zM663.3 325.5l32.8-116.9h6.3l32.1 116.9h-71.2z" p-id="8862" fill="#177cb0"></path><path d="M806.8 818.4H677.2v-0.4l132.6-188.9c1.1-1.6 1.7-3.4 1.7-5.4v-36.4c0-5.1-4.2-9.3-9.3-9.3h-204c-5.1 0-9.3 4.2-9.3 9.3v43c0 5.1 4.2 9.3 9.3 9.3h122.6v0.4L587.7 828.9c-1.1 1.6-1.7 3.4-1.7 5.4v36.4c0 5.1 4.2 9.3 9.3 9.3h211.4c5.1 0 9.3-4.2 9.3-9.3v-43c0.1-5.1-4.1-9.3-9.2-9.3z" p-id="8863" fill="#177cb0"></path><path d="M416 702h-76V172c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v530h-76c-6.7 0-10.5 7.8-6.3 13l112 141.9c3.2 4.1 9.4 4.1 12.6 0l112-141.9c4.1-5.2 0.4-13-6.3-13z" p-id="8864" fill="#177cb0"></path></svg>
        </span>
        <span v-show="book.chapters_sort_by == 'desc'" v-on:click="sortChapters">
          <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M839.6 433.8L749 150.5c-1.2-3.9-4.8-6.5-8.9-6.5h-77.4c-4.1 0-7.6 2.6-8.9 6.5l-91.3 283.3c-0.3 0.9-0.5 1.9-0.5 2.9 0 5.1 4.2 9.3 9.3 9.3h56.4c4.2 0 7.8-2.8 9-6.8l17.5-61.6h89l17.3 61.5c1.1 4 4.8 6.8 9 6.8h61.2c1 0 1.9-0.1 2.8-0.4 2.4-0.8 4.3-2.4 5.5-4.6 1.1-2.2 1.3-4.7 0.6-7.1zM663.3 325.5l32.8-116.9h6.3l32.1 116.9h-71.2z" p-id="8695" fill="#177cb0"></path><path d="M806.8 818.4H677.2v-0.4l132.6-188.9c1.1-1.6 1.7-3.4 1.7-5.4v-36.4c0-5.1-4.2-9.3-9.3-9.3h-204c-5.1 0-9.3 4.2-9.3 9.3v43c0 5.1 4.2 9.3 9.3 9.3h122.6v0.4L587.7 828.9c-1.1 1.6-1.7 3.4-1.7 5.4v36.4c0 5.1 4.2 9.3 9.3 9.3h211.4c5.1 0 9.3-4.2 9.3-9.3v-43c0.1-5.1-4.1-9.3-9.2-9.3z" p-id="8696" fill="#177cb0"></path><path d="M310.3 167.1c-3.2-4.1-9.4-4.1-12.6 0L185.7 309c-4.2 5.3-0.4 13 6.3 13h76v530c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8V322h76c6.7 0 10.5-7.8 6.3-13l-112-141.9z" p-id="8697" fill="#177cb0"></path></svg>
        </span>
        <span v-on:click="show_chapters = !show_chapters,show_control = !show_control">
          <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M354 671h58.9c4.7 0 9.2-2.1 12.3-5.7L512 561.8l86.8 103.5c3 3.6 7.5 5.7 12.3 5.7H670c6.8 0 10.5-7.9 6.1-13.1L553.8 512l122.4-145.9c4.4-5.2 0.7-13.1-6.1-13.1h-58.9c-4.7 0-9.2 2.1-12.3 5.7L512 462.2l-86.8-103.5c-3-3.6-7.5-5.7-12.3-5.7H354c-6.8 0-10.5 7.9-6.1 13.1L470.2 512 347.9 657.9c-4.4 5.2-0.7 13.1 6.1 13.1z" p-id="8529" fill="#177cb0"></path><path d="M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32z m-40 728H184V184h656v656z" p-id="8530" fill="#177cb0"></path></svg>
        </span>
      </li>
    </ul>

    <div class="chapters bg" v-show="show_chapters">
      <ul class="list" ref="chapters">
        <li class="border_top" v-for="(v,i) in book.chapters" v-bind:key="i">
          <p @click="book.index=v.index">{{ v.title }}</p>
        </li>
      </ul>
    </div>

    <div
      class="reader_text bg"
      v-if="book.chapterHtml"
      ref="text"
      v-on:click="show_control = !show_control"
      v-html="book.chapterHtml"
    ></div>
    
  </div>
</template>

<script>
// 通过路由接收书籍ID
// 检查阅读记录，设置索引
// 书籍ID -> 请求目录
// 根据索引加载章节

import config from "../config.js";
import axios from "axios";
import Loading from "@/components/Loading.vue";

export default {
  name: "reader",
  components: {
    Loading
  },
  data: function() {
    return {
      book: {
        id: null,
        name: "",
        index: null,
        chapters: [],
        chapters_sort_by:"asc",
        chapterHtml: "",
        chapterCache:{}
      },
      show_control: 0,
      show_loading: 0,
      show_chapters:0,
    };
  },
  mounted: function() {
    // parse book id and book name from router
    this.book.id = this.$route.params.id;
    this.book.name = this.$route.params.name;
    if (!this.book.name){
      this.book.name = JSON.parse(localStorage.history)[this.book.id].name;
    }
    
    console.log(this.book.id,this.book.name);
  
    // build or update book cache
    // cache as localStorage.history {"id":{"name","index"}}

    if (!localStorage.history) {
      localStorage.history = JSON.stringify({});
    }
    
    // set document title as book name
    document.title = this.book.name;

    // fetch catalogue of this book 
    this.fetchCatalogue();

  },

  methods: {
    fetchChapter: function() {
      this.show_loading = 1;
      axios
        .get(
          config.apis.book + this.book.id + "/chapter/" + this.book.index,
          {
            headers: {
              "x-api-code": localStorage["x-api-code"]
            }
          }
        )
        .then(response => {
          this.book.chapterCache[this.book.id] = response.data.content;
          if (response.data.content) {
            this.book.chapterHtml = "";
            for (let i = 0; i < response.data.content.length; i++) {
              this.book.chapterHtml +=
                "<p>" +
                response.data.content[i].replace(/^\s+|\s+$/g, "") +
                "</p>";
            }
          }
        })
        .then(response => {
          // update history
          let h =JSON.parse(localStorage.history);
          h[this.book.id].index = this.book.index;
          localStorage.history = JSON.stringify(h);
          document.title = this.book.chapters[this.book.index].title + " - " + this.book.name;
        })
        .catch((error) => {
          if (error.response.status == 404) {
            alert("错误代码 404");
          } else if (error.response.status in { 400: "", 401: "", 403: "" }) {
            alert("错误代码 400/401/403");
            delete localStorage["x-api-code"];
            location.assign("/#/login");
          } else {
            alert("意外错误");
          }
        })
        .finally(() => {
          this.$refs.text.scrollTop = 0;
          this.show_chapters = 0;
          this.show_control = 0;
          this.show_loading = 0;
        });
    },
    
    indexChange: function(N) {
      this.show_loading = 1;
      let a = Number(this.book.index)+Number(N);
      if (this.book.chapters[a]){
        this.book.index = a;
      }
      else{
        if (a == -1){
          alert("已经是开始位置了");
        }
        else if(a == this.book.chapters.length){
          alert("已经是结束位置了");
        }
        else {
          alert("奇怪的错误");
        }
        this.book.index = 0;
        this.fetchChapter();
      }
    },

    fetchCatalogue: function() {
      this.show_loading = 1;
      axios
        .get(
          config.apis.book + this.book.id + "/chapters",
          {
            headers: {
              "x-api-code": localStorage["x-api-code"]
            }
          }
        )
        .then(response => {          
          if (response.data.chapters){
            this.book.chapters = response.data.chapters;
          }else{
            alert("获取章节信息时出错");
          }
        })
        .then(response => {          
          // fetch book catalogue succussful, then add book info to history
          let h =JSON.parse(localStorage.history);
          if (h[this.book.id]){
            this.book.index = h[this.book.id].index;
          }else{
            this.book.index = 0;
            h[this.book.id] = {"name":this.book.name,"index":this.book.index};
            localStorage.history = JSON.stringify(h);
          }
        })
        .catch((error) => {
          if (error.response.status == 404) {
            alert("错误代码 404");
          } else if (error.response.status in { 400: "", 401: "", 403: "" }) {
            alert("错误代码 400/401/403");
            delete localStorage["x-api-code"];
            location.assign("/#/login");
          } else {
            alert("意外错误");
          }
        })
        .finally(() => {
          this.show_loading = 0;
        });
    },

    sortChapters:function () {
      // order 'desc' 'asc'
      if (this.book.chapters_sort_by == "asc"){
        this.book.chapters_sort_by = "desc";
      }else{
        this.book.chapters_sort_by = "asc";
      }
      function getSortFun(order, sortBy) {
        let ordAlpah = (order == 'asc') ? '>' : '<';
        let sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + '?1:-1');
        return sortFun;
      }
      this.book.chapters.sort(getSortFun(this.book.chapters_sort_by, 'index'));
    }
  },
  watch: {
    "book.index": function() {
      this.fetchChapter();
    }
  }
};
</script>

<style>
.reader_text {
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  -webkit-overflow-scrolling: touch;
  padding: 15px;
  overflow-y: scroll;
}

.reader_text p {
  text-indent: 32px;
  line-height: 32px;
  word-wrap: break-word;
  font-size: 16px;
}


.control {
  position: fixed;
  bottom: 0;
  width: 100%;
  z-index: 2;
  padding: 5px;
  height: 50px;
}

.control > li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 30px;
  color: #177cb0;
}

.control span {
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bolder;
  font-size: 20px;
  line-height: 20px;
}
.control span svg {
  width: 25px;
  height: 25px;
}
.control > li p {
  font-size: 12px;
}

.control input {
  width: 100px;
  font-size: 10px;
  line-height: 20px;
  color: #177cb0;


  background: transparent;
  text-align: center;
}

.chapter_control {
  top: 0;
  z-index: 3;
  
}

.list {
  display: block;
  overflow: auto;
}

.chapters {
  position: fixed;
  height: 100%;
  bottom: 0;
  top: 0;
  left: 0;
  right: 0;
  z-index: 2;
  overflow-y: scroll;
  padding: 60px 30px;
  
}
.chapters li{
  padding: 10px;
  list-style: none;
  cursor: pointer;
}

.chapters li p{
  font-size: 14px;
  line-height: 20px;
  list-style: none;
  color: #177cb0;
  font-weight: lighter;
}

</style>
